package com.atguigu.crowd.mvc.controller;

import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.RoleService;
import com.autguigu.crowd.constant.CrowdConstant;
import com.autguigu.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * role的Controller
 *
 * @author wmb
 *
 * @since 2021-1-21
 */
@Controller
public class RoleController {

    @Autowired
    @Qualifier("roleService")
    private RoleService roleService;

    @ResponseBody
    @RequestMapping(value = "/role/delete/by/role/id/array.json", method = RequestMethod.POST)
    public ResultEntity<String> removeByRoleIdArray(@RequestBody List<Integer> roleIdList) {
        roleService.removeRole(roleIdList);
        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @RequestMapping(value = "/role/update.json", method = RequestMethod.POST)
    public ResultEntity<String> updateRole(@RequestBody Role role) {
        roleService.updateRole(role);
        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @PostMapping(value = "/role/save.json")
    public ResultEntity<String> saveRole(@RequestBody Role role) {
        roleService.saveRole(role);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('部长')")
    @ResponseBody
    @RequestMapping(value = "/role/get/page/info.json", method = RequestMethod.POST)
    public ResultEntity<PageInfo<Role>> getPageInfo(
                            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                            @RequestParam(value = "keyword", defaultValue = "") String keyword) {

        // 调用Service方法获取分页数据
        PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);
        if (pageInfo != null) {
            return ResultEntity.successWithData(pageInfo);
        } else {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ROLE_QUERY_FAILED);
        }
    }

}
